<template>
  <div class="online-pay-page">
    <div v-if="loading" class="loading-state">
      <div class="loading-text">加载中...</div>
    </div>

    <div v-else-if="payInfo" class="pay-content">
      <!-- 支付信息 -->
      <div class="pay-info-section">
        <div class="pay-info-row">
          <span class="label">支付流水号</span>
          <span class="value">{{ payInfo.payNo || '--' }}</span>
        </div>
        <div class="pay-info-row">
          <span class="label">支付金额</span>
          <span class="value">{{ formatAmount(payInfo.totalAmount || payInfo.paidAmount) }}</span>
        </div>
      </div>

      <!-- 二维码 -->
      <div class="qr-code-section">
        <div v-if="payInfo.qrCodeUrl" class="qr-wrapper">
          <img :src="payInfo.qrCodeUrl" alt="支付二维码" />
        </div>
        <div v-else class="qr-placeholder">
          <p>暂未获取到二维码</p>
          <p class="hint">请确认后端返回字段 qrCodeUrl 已对接</p>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <nut-button type="default" block @click="handleCancel">取消</nut-button>
        <nut-button type="primary" block @click="handleShare">分享支付链接</nut-button>
      </div>
    </div>

    <div v-else class="empty-state">
      <nut-empty description="支付信息不存在" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showDialog } from '@nutui/nutui';
  import { fetchPayInfo, cancelPay, type OrderPayInfo } from '@/api/order';

  const router = useRouter();
  const route = useRoute();

  const loading = ref(false);
  const payInfo = ref<OrderPayInfo | null>(null);

  // 格式化金额
  const formatAmount = (amount?: number) => {
    if (amount === undefined || amount === null) return '--';
    return `¥ ${amount.toFixed(2)}`;
  };

  // 获取支付链接
  const getPayLink = () => {
    if (!payInfo.value?.payId) return '';
    // 构建支付链接
    const baseUrl = window.location.origin;
    const basePath = import.meta.env.BASE_URL || '/';
    // 使用线上支付页面路径
    return `${baseUrl}${basePath}order/online-pay?payId=${payInfo.value.payId}`;
  };

  // 加载支付信息
  const loadPayInfo = async () => {
    const payId = route.query.payId as string;
    if (!payId) {
      showToast.text('支付ID不能为空');
      router.back();
      return;
    }

    try {
      loading.value = true;
      const { code, data, msg }: any = await fetchPayInfo(payId);
      if (code !== 200) {
        showToast.text(msg || '获取支付信息失败');
        return;
      }
      payInfo.value = data as OrderPayInfo;
    } catch (error: any) {
      console.error('获取支付信息失败', error);
      showToast.text(error?.message || '获取支付信息失败');
    } finally {
      loading.value = false;
    }
  };

  // 取消支付
  const handleCancel = () => {
    if (!payInfo.value?.payId) {
      showToast.text('支付ID不存在');
      return;
    }

    showDialog({
      title: '提示',
      content: '确定要取消本次支付吗？',
      onOk: async () => {
        try {
          await cancelPay({ payId: payInfo.value!.payId! });
          showToast.text('取消成功');
          router.back();
        } catch (error: any) {
          console.error('取消支付失败', error);
          showToast.text(error?.message || '取消支付失败');
        }
      },
    });
  };

  // 分享支付链接
  const handleShare = async () => {
    const payLink = getPayLink();
    if (!payLink) {
      showToast.text('支付链接生成失败');
      return;
    }

    try {
      // 复制到剪贴板
      await navigator.clipboard.writeText(payLink);
      showToast.text('支付链接已复制到剪贴板');
    } catch (error) {
      // 降级方案：使用传统方法
      const textArea = document.createElement('textarea');
      textArea.value = payLink;
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        showToast.text('支付链接已复制到剪贴板');
      } catch (err) {
        console.error('复制失败', err);
        showToast.text('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    }
  };

  // 初始化
  onMounted(() => {
    loadPayInfo();
  });
</script>

<style lang="scss" scoped>
  .online-pay-page {
    min-height: 100vh;
    background-color: #fff;
    padding: 20px;
    display: flex;
    flex-direction: column;
  }

  .loading-state {
    padding: 100px 20px;
    text-align: center;

    .loading-text {
      font-size: 28px;
      color: #666;
    }
  }

  .pay-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .pay-info-section {
    margin-bottom: 40px;

    .pay-info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      font-size: 28px;

      .label {
        color: #333;
        font-weight: 500;
      }

      .value {
        color: #333;
        font-weight: 600;
      }
    }
  }

  .qr-code-section {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;

    .qr-wrapper {
      width: 300px;
      height: 300px;
      background-color: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .qr-placeholder {
      text-align: center;
      color: #999;
      font-size: 24px;

      p {
        margin: 8px 0;
      }

      .hint {
        font-size: 22px;
        color: #ccc;
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 16px;
    padding-bottom: 20px;

    .nut-button {
      flex: 1;
    }
  }

  .empty-state {
    padding: 100px 20px;
    text-align: center;
  }
</style>

